<template>
  <div class="inspectionSheet">
    <el-descriptions title="质量检验表" :column="6" border>
      <el-descriptions-item :span="6" label="检验阶段">
        <div>
          <el-radio-group v-model="ruleForm.checkStage">
            <el-radio v-for="item, index in radioList" :key="index" :label="item">{{ item.checkStageName
              }}</el-radio>
          </el-radio-group>
        </div>
        <span class="message">{{ validateMsg.checkStage }}</span>
      </el-descriptions-item>
      <el-descriptions-item :span="2" label="供应商">
        <el-input v-model="ruleForm.supplier" placeholder="请输入供应商名称"></el-input>
        <span class="message">{{ validateMsg.supplier }}</span>
      </el-descriptions-item>
      <el-descriptions-item :span="2" label="检验时间">
        <el-date-picker class="w100p" v-model="ruleForm.checkTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择检验时间">
        </el-date-picker>
        <span class="message">{{ validateMsg.checkTime }}</span>
      </el-descriptions-item>
      <el-descriptions-item :span="2" label="码单号">
        <el-input v-model="ruleForm.codeNo" placeholder="请输入码单号"></el-input>
        <span class="message">{{ validateMsg.codeNo }}</span>
      </el-descriptions-item>

      <template v-if="!ncOrg">
        <el-descriptions-item :span="2" label="投入设施">
          <el-select class="w100p" v-model="ruleForm.facilityId" clearable filterable placeholder="请选择设施名称" @change="getFacilityName">
            <el-option v-for="(item, index) in facilityList" :key="index" :label="item.pondName" :value="item.fishPondId" />
          </el-select>
          <span class="message">{{ validateMsg.facilityId }}</span>
        </el-descriptions-item>

        <el-descriptions-item :span="2" label="检验品种">
          <el-select v-model="ruleForm.plantVarietyId" class="w100p" placeholder="请选择品种" @change="getPlantVarietyName">
            <el-option v-for="item, index in varietyList" :key="index" :label="item.varietyName" :value="item.fishVarietyId"></el-option>
          </el-select>
          <span class="message">{{ validateMsg.plantVarietyId }}</span>
        </el-descriptions-item>

        <el-descriptions-item :span="2" label="品种规格">
          <el-select v-model="ruleForm.specificationId" class="w100p" clearable filterable placeholder="请选择规格" @change="getSpecificationName">
            <el-option v-if="ruleForm.plantVarietyId == item.fishVarietyId" v-for="item, index in specificationList" :key="index" :label="item.specificationName" :value="item.specificationId" />
          </el-select>
          <span class="message">{{ validateMsg.specificationId }}</span>
        </el-descriptions-item>
      </template>
      <template v-if="ncOrg">
        <el-descriptions-item :span="2" label="检验部门">
          <el-select class="w100p" v-model="ruleForm.facilityId" clearable filterable placeholder="请选择部门名称" @change="getCdptName">
            <el-option v-for="(item, index) in OrgDeptList" :key="index" :label="item.name" :value="item.code" />
          </el-select>
          <span class="message">{{ validateMsg.facilityId }}</span>
        </el-descriptions-item>

        <el-descriptions-item :span="2" label="检验品种">
          <el-select v-model="ruleForm.plantVarietyId" class="w100p" placeholder="请选择品种" @change="getMaterialName">
            <el-option v-for="item, index in MaterialList" :key="index" :label="item.name" :value="item.code"></el-option>
          </el-select>
          <span class="message">{{ validateMsg.plantVarietyId }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="品种规格">
          <el-select v-model="ruleForm.specificationId" class="w100p" clearable filterable placeholder="请选择规格" @change="getDefdoc2Name">
            <el-option v-for="item, index in Defdoc2List" :key="index" :label="item.name" :value="item.code" />
          </el-select>
          <span class="message">{{ validateMsg.specificationId }}</span>
        </el-descriptions-item>
      </template>

      <el-descriptions-item :span="2" label="重量">
        <el-input type="number" v-model="ruleForm.weight" placeholder="请输入重量" @change="handleChangeWeight">
          <template slot="append">斤</template>
        </el-input>
        <span class="message">{{ validateMsg.weight }}</span>
      </el-descriptions-item>
      <el-descriptions-item :span="2" label="尾数">
        <el-input type="number" v-model="ruleForm.num" placeholder="请输入尾数" @change="handleChangeNum">
          <template slot="append">尾</template>
        </el-input>
        <span class="message">{{ validateMsg.num }}</span>
      </el-descriptions-item>
      <el-descriptions-item :span="2" label="检验人">
        <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人" @change="handleChangePerson">
          <el-option v-for="item, index in person" :key="index" :label="item.staffName" :value="item.staffId"></el-option>
        </el-select>
        <span class="message">{{ validateMsg.staffId }}</span>
      </el-descriptions-item>
      <el-descriptions-item :span="6" label="检验范畴">
        <el-checkbox-group v-model="ruleForm.inspectionScope" @change="handleChangeScope">
          <el-checkbox v-for="item, index in rowList" :key="index" :label="item">{{ item.name
            }}</el-checkbox>
        </el-checkbox-group>
      </el-descriptions-item>
    </el-descriptions>
    <div class="th flex" v-show="ruleForm.inspectionScope && ruleForm.inspectionScope.length > 0">
      <div class="f_1 content th_title">范畴</div>
      <div class="f_2 ">
        <div class="flex">
          <div class="content f_2_1 th_title">检验科目</div>
          <div class="content f_2_2 th_title">检验标准</div>
          <div class="content f_2_3 th_title">检验结果</div>
        </div>
      </div>
    </div>
    <div class="content danger" v-show="!(ruleForm.inspectionScope && ruleForm.inspectionScope.length > 0)">请先选择范畴！
    </div>
    <div v-if="resetRadio" class="tr flex" v-show="item.subject && item.subject.length" v-for="item, index in rowList" :key="index">
      <div class="f_1 content">{{ item.name }}</div>
      <div class="f_2">
        <div class="flex" v-for="sub, i in item.subject" :key="i">
          <div class="content f_2_1">{{ sub.checkScopeName }}</div>
          <div class="content f_2_2">{{ sub.checkStandard }}</div>
          <div class="content f_2_3">
            <el-radio-group v-model="sub.checkResult">
              <!-- @change="(e) => { handleCheckResult(e, index, i) }" -->
              <el-radio label="合格">合格</el-radio>
              <el-radio label="不合格">不合格</el-radio>
              <el-radio label="无需检验">无需检验</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
    </div>
    <el-descriptions :column="6" border>

      <template v-if="userType == 'INSPECTOR'">
        <el-descriptions-item :span="6" label="检验员结论" label-class-name="my-label">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="ruleForm.staffResult">
          </el-input>
        </el-descriptions-item>
        <el-descriptions-item :span="6" label="操作 (提交给技术员审核)" label-class-name="my-label">
          <el-button type="primary" plain @click="submit">提交表单</el-button>
        </el-descriptions-item>
      </template>

      <template v-if="userType == 'TECHNICIAN'">
        <el-descriptions-item :span="6" label="技术员结论">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="ruleForm.technicianResult">
          </el-input>
        </el-descriptions-item>
        <el-descriptions-item :span="1" label="操作 (提交给场长审核)">
          <el-button type="primary" plain @click="submit">提交表单</el-button>
        </el-descriptions-item>

        <el-descriptions-item :span="5" label="结果评定">
          <el-radio-group v-model="ruleForm.technicianStatus">
            <el-radio :label="'合格'">合格准入</el-radio>
            <el-radio :label="'不合格'">不合格拒入</el-radio>
            <el-radio :label="'让步'">让步接收</el-radio>
          </el-radio-group>
        </el-descriptions-item>
        <el-descriptions-item :span="5" label="结果评定">

        </el-descriptions-item>
      </template>

      <template v-if="userType == 'FARMER'">
        <el-descriptions-item :span="6" label="场长结论">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="ruleForm.farmResult">
          </el-input>
        </el-descriptions-item>
        <el-descriptions-item :span="1" label="操作">
          <el-button type="primary" plain @click="submit">确认提交</el-button>
        </el-descriptions-item>
        <el-descriptions-item :span="5" label="结果评定">
          <el-radio-group v-model="ruleForm.farmStatus">
            <el-radio :label="'合格'">合格准入</el-radio>
            <el-radio :label="'不合格'">不合格拒入</el-radio>
            <el-radio :label="'让步'">让步接收</el-radio>
          </el-radio-group>
        </el-descriptions-item>
      </template>
      <!-- // {INSPECTOR: "检验员", TECHNICIAN: "技术员", FARMER: "场长"} -->
    </el-descriptions>
  </div>
</template>

<script>
import MainSlot from "@/components-production-management/MainSlot";
import inspectionPhase from "@/api/quality-management/inspectionPhase.js";
import inspectionScope from "@/api/quality-management/inspectionScope.js";
import inspectionSubject from "@/api/quality-management/inspectionSubject.js";
import inspectionManagement from "@/api/quality-management/inspectionManagement";
import varietyManagement from "@/api/basic-info-manage/fishVariety";
import facilityManagement from "@/api/basic-info-manage/fishPond";
import specificationManagement from "@/api/basic-info-manage/specification/index";
import inspectorAssignment from "@/api/quality-management/inspectorAssignment.js";
import ncbasicinfoApi from "@/api/nc-basic-info/index.js";

export default {
  components: { MainSlot },
  props: {
    userType: {
      type: String,
      default: () => {
        return "";
      },
    },
    isEdit: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      resetRadio: true,
      loading: false,
      validateMsg: {},
      radioList: [],
      rowList: [
        {
          name: "",
          subject: [],
        },
      ],
      ruleForm: {
        checkTime: this.$formatTime(new Date(), "yyyy-MM-dd HH:mm:ss"),
        inspectionScope: [],
      },
      person: [],
      facilityList: [],
      varietyList: [],
      specificationList: [],
      inspectionScopeList: [],

      ncOrg: sessionStorage.ncOrg || "",
      OrgDeptList: [], //部门
      MaterialList: [], //物料品种
      Defdoc2List: [], //活鱼品规
    };
  },
  // computed: {
  //   person() {
  //     return this.$store.state.initData.person || [];
  //   },
  // },
  watch: {
    ruleForm: {
      handler(v) {
        for (let key in v) {
          this.validateForm(v, key);
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.getRadioList();
    this.getInspectionScope();
    this.initData();
  },
  methods: {
    async initData() {
      let { data: person } = await inspectorAssignment.queryByCondition({
        type: "INSPECTOR",
      });
      this.person = person;
      console.log(person, "-----------------------");
      //规格
      console.log("ncOrg", this.ncOrg);
      let { data: specificationList } =
        await specificationManagement.queryByCondition({});
      this.specificationList = specificationList;
      if (this.ncOrg) {
        let { data: OrgDeptList } = await ncbasicinfoApi.queryOrgDept({
          pk_org: this.ncOrg,
        });
        this.OrgDeptList = OrgDeptList || [];
        //物料品种
        let { data: MaterialList } = await ncbasicinfoApi.queryMaterial({
          pk_parent: "1001A110000000003G58",
        });
        this.MaterialList = MaterialList || [];
        //活鱼品规
        let { data: Defdoc2List } = await ncbasicinfoApi.queryDefdoc2();
        this.Defdoc2List = Defdoc2List || [];
      } else {
        //获取品种；
        let { data: varietyList } = await varietyManagement.queryByCondition(
          {}
        );
        this.varietyList = varietyList || [];
        //获取养殖设施；
        let { data: facilityList } =
          await facilityManagement.queryByCondition(); //查询鱼塘列表 //bindBatch:true 查询绑定了批次的鱼塘
        this.facilityList = facilityList || [];
      }
    },
    //检验阶段
    async getRadioList() {
      let res = await inspectionPhase.queryByCondition({});
      this.radioList = res.data || [];
    },
    //检验范畴
    async getInspectionScope() {
      let res = await inspectionScope.queryByCondition({});
      this.inspectionScopeList = res.data || [];
      this.rowList = this.inspectionScopeList.map((item) => {
        return {
          name: item.scopeTypeName,
          checkScopeTypeId: item.checkScopeTypeId,
          subject: [],
        };
      });
    },
    handleChangeScope(list) {
      if (!list || list.length == 0) {
        this.rowList = this.rowList.map((item) => {
          return { ...item, subject: [] };
        });
      } else {
        let idList = list.map((item) => item.checkScopeTypeId);
        list.forEach((item) => {
          this.getInspectionSubject(item.checkScopeTypeId, idList);
        });
      }
    },
    handleChangeWeight(e) {
      if (!e || e < 0) {
        this.$message.warning("请输入大于0的数");
        this.ruleForm.weight = Math.abs(e || 0);
      }
    },
    handleChangeNum(e) {
      if (e % 1 !== 0 || e < 0) {
        this.$message.warning("请输入大于0的整数");
        this.ruleForm.num = Math.floor(Math.abs(e || 0));
      }
    },
    //获取科目
    async getInspectionSubject(checkScopeTypeId, idList) {
      let res = await inspectionSubject.queryByCondition({ checkScopeTypeId });
      this.rowList.forEach((item) => {
        if (item.checkScopeTypeId == checkScopeTypeId) {
          let subjectList = null;
          if (item.subject && item.subject.length > 0) {
            subjectList = JSON.parse(JSON.stringify(item.subject));
          } else {
            subjectList = null;
          }
          item.subject = res.data.map((d, index) => {
            return {
              ...d,
              checkResult: subjectList
                ? subjectList[index].checkResult || ""
                : "",
            };
          });
        }
        if (!idList.includes(item.checkScopeTypeId)) {
          item.subject = [];
        }
      });
      console.log(this.rowList);
    },
    getPersonName() {
      if (!this.ruleForm.staffId) return;
      let result = this.person.find(
        (obj) => obj.personNo == this.ruleForm.staffId
      );
      this.$set(this.ruleForm, "staffName", result.person.name || "");
    },
    // 没有Nc情况下品种规格改变
    getSpecificationName() {
      if (!this.ruleForm.specificationId) return;
      let result = this.specificationList.find(
        (obj) => obj.specificationId == this.ruleForm.specificationId
      );
      this.$set(
        this.ruleForm,
        "specificationName",
        result.specificationName || ""
      );
    },
    // 有Nc情况下品种规格改变

    getDefdoc2Name() {
      if (!this.ruleForm.specificationId) return;
      let result = this.Defdoc2List.find(
        (obj) => obj.code == this.ruleForm.specificationId
      );
      this.$set(this.ruleForm, "specificationName", result.name || "");
    },
    getFacilityName() {
      if (!this.ruleForm.facilityId) return;
      let result = this.facilityList.find(
        (obj) => obj.fishPondId == this.ruleForm.facilityId
      );
      this.$set(this.ruleForm, "facilityName", result.pondName || "");
    },
    //有nc获取投入部门
    getCdptName() {
      if (!this.ruleForm.facilityId) return;
      let result = this.OrgDeptList.find(
        (obj) => obj.code == this.ruleForm.facilityId
      );
      this.$set(this.ruleForm, "facilityName", result.name || "");
    },
    //无nc检验品种
    getPlantVarietyName() {
      if (!this.ruleForm.plantVarietyId) return;
      let result = this.varietyList.find(
        (obj) => obj.fishVarietyId == this.ruleForm.plantVarietyId
      );
      console.log(result, this.facilityList);
      this.$set(this.ruleForm, "plantVarietyName", result.varietyName || "");
      this.$set(this.ruleForm, "specificationId", "");
      this.$set(this.ruleForm, "specificationName", "");
    },
    //有Nc检验品种
    getMaterialName() {
      if (!this.ruleForm.plantVarietyId) return;
      let result = this.MaterialList.find(
        (obj) => obj.code == this.ruleForm.plantVarietyId
      );
      console.log(result, this.varietyList);
      this.$set(this.ruleForm, "plantVarietyName", result.name || "");
    },
    handleChangePerson(id) {
      let row = this.person.find((item) => Number(item.staffId) == id);
      this.$set(this.ruleForm, "staffName", row.staffName);
    },
    handleCheckResult(e, index, childIndex) {
      let subject = JSON.parse(
        JSON.stringify(this.rowList[index].subject[childIndex])
      );
      subject.checkResult = e;
      this.rowList[index].subject[childIndex] = subject;
      this.resetRadio = false;
      this.$nextTick(() => {
        this.resetRadio = true;
      });
    },
    submit() {
      let checkQualityDetailList = [];
      let checkStageId = this.ruleForm.checkStage
        ? this.ruleForm.checkStage.checkStageId || ""
        : "";
      this.rowList.forEach((row) => {
        checkQualityDetailList = checkQualityDetailList.concat(row.subject);
      });
      let params = {
        ...this.ruleForm,
        checkStageId: checkStageId,
        checkQualityDetailList: checkQualityDetailList,
      };
      let filterItem = checkQualityDetailList.filter((item) => {
        return !item.checkResult;
      });
      this.validateForm(params);
      if (Object.keys(this.validateMsg).length) {
        return;
      }
      if (filterItem.length > 0 || checkQualityDetailList.length == 0) {
        this.$message.warning("完善检验项结果再继续提交！");
        return;
      }
      let summit0bj = JSON.parse(
        JSON.stringify({ ...params, status: "TECHNICAL_EVALUATION" })
      );
      if (this.ncOrg) {
        summit0bj.facilityId = "";
        summit0bj.plantVarietyId = "";
        summit0bj.specificationId = "";
      }
      inspectionManagement
        .add(summit0bj)
        .then((res) => {
          console.log(res);
          if (res.success) {
            this.$message.success("操作成功");
            setTimeout(() => {
              this.isResetData();
            }, 1000);
          } else {
            this.$message.warning("操作失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    isResetData() {
      this.$confirm("是否重置当前数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.resetInfo();
          this.$message({
            type: "success",
            message: "重置成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置",
          });
        });
    },
    resetInfo() {
      this.radioList = [];
      this.rowList = [
        {
          name: "",
          subject: [],
        },
      ];
      this.ruleForm = {
        inspectionScope: [],
      };
      this.facilityList = [];
      this.varietyList = [];
      this.specificationList = [];
      this.inspectionScopeList = [];
      this.getRadioList();
      this.getInspectionScope();
      this.initData();
      setTimeout(() => {
        this.validateMsg = {};
      }, 1000);
    },
    validateForm(params, key) {
      params = params || this.ruleForm;
      let validateObj = {
        plantVarietyId: "请选择品种！",
        checkStage: "请选择检验阶段！",
        supplier: "请输入供应商！",
        checkTime: "请选择检验时间！",
        codeNo: "请输入码单号！",
        facilityId: "请选择设施！",
        staffId: "请选择检验员！",
        specificationId: "请选择规格！",
        num: "请输入尾数！",
        weight: "请输入重量！",
      };
      let validate = {};
      if (key) {
        console.log(params[key]);
        if (params[key]) {
          delete this.validateMsg[key];
        } else {
          this.validateMsg[key] = validateObj[key] || "";
        }
        console.log(this.validateMsg);
      } else {
        for (let key in validateObj) {
          if (!params[key]) {
            validate[key] = validateObj[key];
          }
        }
        this.validateMsg = validate;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.inspectionSheet {
  width: 100%;
  height: 100%;
  padding: 0 10px;
  overflow-y: auto;
}

.flex {
  display: flex;
  justify-content: flex-start;

  .f_1 {
    width: 10%;
  }

  .f_2 {
    width: 90%;
  }

  .f_2_1 {
    width: 15%;
  }

  .f_2_2 {
    width: 65%;
  }

  .f_2_3 {
    width: 30%;
  }
}

.th {
  .th_title {
    font-weight: bold;
  }
}

.tr {
  color: #505050;
}

.titleLable {
  width: 100%;
  box-sizing: border-box;
  color: #909399;
  background: #fafafa;
}

.content {
  border: 1px solid #ebeef5;
  box-sizing: border-box;
  text-align: left;
  font-weight: 400;
  font-size: 12px;
  line-height: 1.5;
  padding: 6px 10px;
}

.message {
  color: red;
}

::v-deep .my-label {
  width: 300px !important;
}
</style>